<?php

namespace Shared;

class SQLLogger extends \Cornerstone\Object implements \Doctrine\DBAL\Logging\SQLLogger {

	private $sTime;
	private $sql;
	public $logAbove = 0.1;
	public static $total = 0;
	public static $totalQueries = 0;

	public function startQuery($sql, array $params = null, array $types = null) {
		self::$totalQueries++;

		if (!$params) {
			$params = [];
		}
		if (!$types) {
			$types = [];
		}

		$time = explode(' ', microtime(true));
		$this->sTime = $time[0];
		try {
			foreach ($params as $key => $param) {

				if ($param instanceof \DateTime) {
					$params[(string) $key] = $param->format('Y-m-d H:i:s');
				} else {
					if (is_object($param) || is_array($param)) {
						$params[(string) $key] = '';
					}
				}
			}
			$sql = str_replace('?', '%s', $sql);
			foreach ($params as $key => $param) {
				if ($param === null) {
					$param = 'null';
				} elseif (!$types[$key] || $types[$key] == 2) {
					$param = "'{$param}'";
				}

				$params[$key] = $param;
			}

			if ($params) {
				$this->sql = call_user_func_array('sprintf', array_merge((array) str_replace('?', '%s', $sql), $params));
			} else {
				$this->sql = $sql;
				;
			}
		} catch (\Exception $e) {
//			\Shared\NodeLog::exception($e);
		}
	}

	public function stopQuery() {
		$time = explode(' ', microtime(true));
		$execTime = $time[0] - $this->sTime;

		self::$total+=$execTime;
		echo \sprintf('<br />+%0.5fs (%0.5fs) %s %s ', $execTime, self::$total, $this->sql, PHP_EOL . PHP_EOL);
	}

	public function __destruct() {
		echo 'Total Queries : ' . self::$totalQueries;
	}

}
